package com.cskaoyan.market.service;

import com.cskaoyan.market.db.domain.MarketRegion;
import com.cskaoyan.market.db.domain.MarketRegionExample;
import com.cskaoyan.market.db.mapper.MarketRegionMapper;
import com.cskaoyan.market.util.MybatisUtils;
import com.cskaoyan.market.vo.MarketRegionVo;
import org.apache.ibatis.session.SqlSession;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AdminRegionServiceImpl implements AdminRegionService {

    @Override
    public List<MarketRegionVo> list(){
        SqlSession session = MybatisUtils.getSession();
        MarketRegionMapper marketRegionMapper= session.getMapper(MarketRegionMapper.class);
        List<MarketRegion> marketRegions=marketRegionMapper.selectByExample(new MarketRegionExample());
        session.close();
        Map<Integer, List<MarketRegion>> data=groupBuPid(marketRegions);
        List<MarketRegionVo> vos=new ArrayList<>();
        List<MarketRegion> provinces=data.get(0);
        for (MarketRegion province : provinces) {
            //需要做的事情是把marketRegion转换成vo对象
            List<MarketRegionVo> cityVos = new ArrayList<>();
            MarketRegionVo provinceVo = new MarketRegionVo(province.getId(), province.getName(), province.getType(), province.getCode(), cityVos);
            //处理city 利用省id编号来获得
            List<MarketRegion> cities = data.get(province.getId());
            for (MarketRegion city : cities) {
                //把city转换 成vo
                List<MarketRegionVo> areaVos = new ArrayList<>();

                //处理区
                List<MarketRegion> areas = data.get(city.getId());
                for (MarketRegion area : areas) {
                    MarketRegionVo areaVo = new MarketRegionVo(area.getId(), area.getName(), area.getType(), area.getCode(), null);
                    areaVos.add(areaVo);
                }

                MarketRegionVo cityVo = new MarketRegionVo(city.getId(), city.getName(), city.getType(), city.getCode(), areaVos);
                cityVos.add(cityVo);
            }


            vos.add(provinceVo);
        }

        return vos;
    }

    private Map<Integer, List<MarketRegion>> groupBuPid(List<MarketRegion> marketRegions) {
        Map<Integer, List<MarketRegion>> map = new HashMap<Integer, List<MarketRegion>>();
        for (MarketRegion region : marketRegions) {
            Integer pid = region.getPid();
            List<MarketRegion> list = map.get(pid);
            if(list == null){
                list = new ArrayList<>();
            }
            list.add(region);
            map.put(pid, list);
        }
        return map;
    }
}
